<?php
// +----------------------------------------------------------------------
// | INPHP
// | Copyright (c) 2023 https://inphp.cc All rights reserved.
// | Licensed ( https://opensource.org/licenses/MIT )
// | Author: 幺月儿(https://gitee.com/lulanyin) Email: inphp@qq.com
// +----------------------------------------------------------------------
// | 响应数据
// +----------------------------------------------------------------------
namespace Inphp\Core\Object;

class Message
{
    /**
     * 事件，用于 Ws
     * @var string|null
     */
    public ?string $event = null;

    /**
     * 错误码
     * @var int
     */
    public int $error = 0;

    /**
     * 消息
     * @var string|null
     */
    public ?string $message = null;

    /**
     * 数据
     * @var mixed
     */
    public mixed $data = null;

    /**
     * 初始化
     * Message constructor.
     * @param array $values
     */
    public function __construct(array $values = [])
    {
        $this->event = $values["event"] ?? null;
        $this->error = $values["error"] ?? 0;
        $this->message = $values["message"] ?? "success";
        $this->data = $values["data"] ?? null;
    }

    /**
     * @param null $value
     * @return Message
     */
    public function event($value = null): Message
    {
        $this->event = $value;
        return $this;
    }

    /**
     * @param int $value
     * @return Message
     */
    public function error(int $value = 0): Message
    {
        $this->error = $value;
        return $this;
    }

    /**
     * @param null $value
     * @return Message
     */
    public function message($value = null): Message 
    {
        $this->message = $value;
        return $this;
    }

    /**
     * @param null $value
     * @return Message
     */
    public function data($value = null): Message
    {
        $this->data = $value;
        return $this;
    }

    /**
     * 生成JSON
     * @return string
     */
    public function toJson(): string
    {
        //返回JSON格式数据
        return json_encode($this->toArray(), JSON_UNESCAPED_UNICODE);
    }

    /**
     * 转换为数据
     * @return array
     */
    public function toArray(): array
    {
        $json = [
            "error"     => $this->error
        ];
        //不为空才加入
        if(!is_null($this->event)){
            $json["event"]  = $this->event;
        }
        if(!is_null($this->message)){
            $json["message"] = $this->message;
        }
        if(!is_null($this->data)){
            $json["data"]   = $this->data;
        }

        return $json;
    }

    public function __toString(): string
    {
        // TODO: Implement __toString() method.
        return $this->toJson();
    }
}